package com.drcoffee.drcoffeemall.service.impl;

import com.drcoffee.drcoffeemall.entry.*;
import com.drcoffee.drcoffeemall.entry.requestBody.PartReq;
import com.drcoffee.drcoffeemall.feign.ErpProviderClient;
import com.drcoffee.drcoffeemall.mapper.AttachmentMapper;
import com.drcoffee.drcoffeemall.mapper.FilePathMapper;
import com.drcoffee.drcoffeemall.service.AttachmentService;
import com.drcoffee.drcoffeemall.util.FileUploadDownloadUtils;
import com.drcoffee.drcoffeemall.util.OSSUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
//@DS("mysql")
public class AttachmentServiceImpl implements AttachmentService {
    final
    AttachmentMapper attachmentMapper;
    final
    FilePathMapper filePathMapper;

    final
    FileUploadDownloadUtils fileUploadDownloadUtils;

    final
    ErpProviderClient erpProviderClient;


    final
    OSSUtil ossUtil;

    public AttachmentServiceImpl(AttachmentMapper attachmentMapper, FileUploadDownloadUtils fileUploadDownloadUtils, FilePathMapper filePathMapper, OSSUtil ossUtil, ErpProviderClient erpProviderClient) {
        this.attachmentMapper = attachmentMapper;
        this.fileUploadDownloadUtils = fileUploadDownloadUtils;
        this.filePathMapper = filePathMapper;
        this.ossUtil = ossUtil;
        this.erpProviderClient = erpProviderClient;
    }


    //    @DS("mysql")
    @Override
    public Object getAttachment(PartReq partReq) {
        String type_sql = "";
        if (Objects.equals(partReq.getPartType(), "P")) {
            type_sql = "AND B.part_code like '7%'";
        } else if (Objects.equals(partReq.getPartType(), "B")) {
            type_sql = "AND B.part_code like '8%'";
        } else if (Objects.equals(partReq.getPartType(), "N")) {
            type_sql = "AND B.part_code like '8%'";
        }
        System.out.println(partReq.getCurrentPage() + "-----------" + partReq.getPageSize());
        PageHelper.startPage(partReq.getCurrentPage(), partReq.getPageSize());
        PageInfo<Attachment> attachmentPage = new PageInfo<>(attachmentMapper.getAttachment(partReq.getMachineId(), type_sql, "%" + partReq.getSearch() + "%"));
        return new ResponseEntity<>(attachmentPage, HttpStatus.OK);
    }

    @Override
    public Map<String, Object> getAttachmentById(String language, Integer dot_id) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            List<String> partCodes = attachmentMapper.getDots(dot_id);
            System.out.println(partCodes);
            List<Attachment> attachments = attachmentMapper.getAttachmentById(language, partCodes);
            System.out.println(attachments);
            resultMap.put("attachments", attachments);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("reason", e.toString());
        }
        return resultMap;
    }

    @Override

    public ResponseEntity<Object> getAttachmentAll(String search, Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<Attachment> attachmentList;
        attachmentList = attachmentMapper.getAttachmentAll("%" + search + "%");
        PageInfo<Attachment> attachmentPage = new PageInfo<>(attachmentList);
        return new ResponseEntity<>(attachmentPage, HttpStatus.OK);
    }

    @Override
    public Map<String, Object> updatepartimgurl(String image_url, String part_code) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            Integer count = attachmentMapper.updatepartimgurl(image_url, part_code);
            resultMap.put("reason", count > 0);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("reason", e.toString());
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> editInfo(Attachment attachment) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            Integer count = attachmentMapper.editInfo(attachment);
            if (count > 0) {
                count = attachmentMapper.editPrice(attachment);
            } else {
                resultMap.put("reason", false);
            }
            resultMap.put("reason", count > 0);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("reason", e.toString());
        }
        return resultMap;
    }


    @Override
//    @DS("oracle")
    public Map<String, Object> updateOCM(Attachment attachment) {
        Map<String, Object> resultMap = new HashMap<>();
        System.out.println("================update2OCM====================");
        try {
            Integer count = 0;
            Date date = new Date();
            SimpleDateFormat ft = new SimpleDateFormat("yyMMdd");
            SimpleDateFormat ft2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat ft3 = new SimpleDateFormat("yyyy-MM-dd");
            //渠道11 和 渠道12 偷懒
            for (Integer i = 11; i <= 12; i++) {
                count = 0;
                String newdocno = "";
                String dandocno = attachmentMapper.getOCMPriceDocno();
                if (dandocno != null && dandocno.trim().length() > 0) {
                    //单号处理
                    if (dandocno.substring(3, 9).equals(ft.format(date))) {
                        String num = dandocno.substring(9);
                        int i_m = Integer.parseInt(num);
                        String str_m = String.valueOf(i_m + 1);
                        String str = "0000";
                        newdocno = "QJG" + dandocno.substring(3, 9) + str.substring(0, 4 - str_m.length()) + str_m;
                    } else {
                        newdocno = "QJG" + ft.format(date) + "0001";
                    }
                    AttNo4OCM attNo4OCM = new AttNo4OCM();
                    attNo4OCM.setDakdocno(newdocno);
                    attNo4OCM.setDakchnl(i.toString());
                    attNo4OCM.setDakddate((ft3.format(date) + " 00:00:00").toString());
                    attNo4OCM.setDakbdate((ft3.format(date) + " 00:00:01").toString());
                    attNo4OCM.setDakcdate(ft2.format(date).toString());
                    attNo4OCM.setDakmdate(ft2.format(date).toString());
                    attNo4OCM.setDakadate(ft2.format(date).toString());
                    attNo4OCM.setDakedate((ft3.format(date) + " 23:59:59").toString());
                    count = attachmentMapper.InsertOCMPriceNo(attNo4OCM);
                    if (count == 0) {
                        resultMap.put("reason", false);
                        break;
                    } else {
                        PartOCM partOCM = new PartOCM();
                        partOCM.setDandocno(newdocno);
                        partOCM.setDangoods(attachment.getPart_code());
                        partOCM.setDanbdate((ft3.format(date) + " 00:00:01").toString());
                        partOCM.setDan008(ft2.format(date).toString());
                        partOCM.setDanedate((ft3.format(date) + " 23:59:59").toString());
                        partOCM.setDan002(i.toString());
                        if (i == 11) {
                            partOCM.setDansprice(attachment.getDealer_price().toString());
                            partOCM.setDan003(attachment.getDealer_price().toString());
                            partOCM.setDan004(attachment.getDealer_price().toString());
                        } else {
                            partOCM.setDansprice(attachment.getPrice().toString());
                            partOCM.setDan003(attachment.getPrice().toString());
                            partOCM.setDan004(attachment.getPrice().toString());
                        }
                        System.out.println(partOCM);
                        count = attachmentMapper.InsertOCMPrice(partOCM);
                        if (count == 0) {
                            resultMap.put("reason", false);
                            break;
                        }
                    }
                    //count = attachmentMapper.InsertOCMPrice(att4OCM);
                } else {
                    resultMap.put("reason", false);
                }
            }
            resultMap.put("reason", count > 0);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("reason", e.toString());
        }
        return resultMap;
    }

    @Override
//    @DS("oracle")
    public List<OCM2Mall> getNewList() {
        System.out.println("================getNewList====================");
        List<OCM2Mall> relist = new ArrayList<>();
        try {

            List<PartOCM> priceList = attachmentMapper.getNewList();
            priceList.forEach(list -> {
//                String part_code = list.getDangoods();
//                String channel = list.getDan002();
//                String price = list.getDan003();
                OCM2Mall ocm2Mall = new OCM2Mall();
                ocm2Mall.setPrice(list.getDan003());
                ocm2Mall.setChannel(list.getDan002());
                ocm2Mall.setPart_code(list.getDangoods());
                relist.add(ocm2Mall);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return relist;
    }

    @Override
    public Map<String, Object> refreshList(List<OCM2Mall> list) {
        Map<String, Object> resultMap = new HashMap<>();
        List erroritem = new ArrayList<>();
        System.out.println("================update2OCM====================");
        try {
            list.forEach(item -> {
                Integer count = attachmentMapper.partExist(item.getPart_code());
                if (count > 0) {
                    count = 0;
                    if (item.getChannel().equals("11")) {
                        count = attachmentMapper.updatePart1(item.getPart_code(), item.getPrice());
                        if (count == 0) {
                            erroritem.add(item.getPart_code());
                        }
                        //erroritem.add(item.getPart_code());

                    } else if (item.getChannel().equals("12")) {
                        count = attachmentMapper.updatePart2(item.getPart_code(), item.getPrice());
                        if (count == 0) {
                            erroritem.add(item.getPart_code());
                        }
                    }
                } else {
                    attachmentMapper.createPart(item.getPart_code());
                }
            });
            resultMap.put("error", erroritem);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(resultMap);
        return resultMap;

    }

    @Override
    public ResponseEntity<Object> insertParts(MultipartFile file, String file_name, Map<String, Object> part) throws IOException {
        String uploadPath = filePathMapper.getUploadPath("G", 1);
        Map<String, Object> fileResultMap = ossUtil.uploadImgPart(file, uploadPath, file_name);
        if ((Integer) fileResultMap.get("code") == -1) {
            return new ResponseEntity<>(new Result(-1, "error", fileResultMap.get("msg").toString(), null), HttpStatus.OK);
        }

        List<Attachment> parts = new ArrayList<>();
        Attachment partCn = new Attachment();
        partCn.setPart_code(part.get("part_code").toString());
        partCn.setPart_name(part.get("part_name").toString());
        partCn.setUnit(part.get("unit").toString());
        partCn.setWeight(Double.parseDouble(part.get("weight").toString()));
        partCn.setMaterial(part.get("material").toString());
        partCn.setPacking(part.get("packing").toString());
        partCn.setType(part.get("type").toString());
        partCn.setLanguage("CN");
        partCn.setImage_url(fileResultMap.get("file_path").toString());

        Attachment partEn = new Attachment();
        partEn.setPart_code(part.get("part_code").toString());
        partEn.setPart_name(part.get("part_name_en").toString());
        partEn.setUnit(part.get("unit_en").toString());
        partEn.setWeight(Double.parseDouble(part.get("weight").toString()));
        partEn.setMaterial(part.get("material_en").toString());
        partEn.setPacking(part.get("packing_en").toString());
        partEn.setType(part.get("type").toString());
        partEn.setLanguage("EN");
        partEn.setImage_url(fileResultMap.get("file_path").toString());

        parts.add(partCn);
        parts.add(partEn);

        Map<String, Object> partPrice = new HashMap<>();
        partPrice.put("part_code", part.get("part_code").toString());
        partPrice.put("price", new BigDecimal((String) part.get("price")));
        partPrice.put("dealer_price", new BigDecimal((String) part.get("dealer_price")));
        partPrice.put("overseas_price", new BigDecimal((String) part.get("overseas_price")));

        System.out.println(parts);
        attachmentMapper.insertParts(parts);
        attachmentMapper.insertPartPrice(partPrice);

        return new ResponseEntity<>(new Result(1, "success", "", null), HttpStatus.OK);
    }

    @Override
    public ResponseEntity<Object> dataCheck() {
        String prefix = "PartsMallFile/parts";
        Map<String, Object> resultMap = new HashMap<>();

        // 校验中英文差异
        Map<String, Object> ce_discrepancy = new HashMap<>();
        List<String> cn_part_list = attachmentMapper.getCnEnDiscrepancy("CN", "EN"); // CN多出EN的
        List<String> en_part_list = attachmentMapper.getCnEnDiscrepancy("EN", "CN"); // CN多出EN的
        ce_discrepancy.put("cn_part_list", cn_part_list);
        ce_discrepancy.put("en_part_list", en_part_list);
        resultMap.put("ce_discrepancy", ce_discrepancy);

        // 校验配件图片是否漏传
        Map<String, Object> img_discrepancy = new HashMap<>();

        List<String> ossFileList = ossUtil.fileEnumeration(); // OSS文件列表
        List<String> partImages = attachmentMapper.getPartImages(); // 数据库文件列表
/*        List<String> newPartImages = partImages.stream()
                .map(s -> (s != null && s.length() > 1) ? prefix + s : s)
                .toList();*/
        List<String> newPartImages = partImages.stream()
                .map(s -> (s != null && s.length() > 1) ? prefix + s : s)
                .collect(Collectors.toList());
        // OSS缺少
        List<String> lack_img_list = new ArrayList<>(newPartImages);
        lack_img_list.removeAll(ossFileList);

        // OSS多出
        List<String> excess_img_list = new ArrayList<>(ossFileList);
        excess_img_list.removeAll(newPartImages);

/*        lack_img_list = lack_img_list.stream()
                .map(s -> (s != null && s.length() > 1) ? s.replaceAll("PartsMallFile/parts", "") : s)
                .toList();*/
        lack_img_list = lack_img_list.stream()
                .map(s -> (s != null && s.length() > 1) ? s.replaceAll("PartsMallFile/parts", "") : s)
                .collect(Collectors.toList());


        // 根据image_url查询配件
        List<String> differencePartCodeImgList = attachmentMapper.getPartCodeByImgUrls(lack_img_list);
        img_discrepancy.put("lack_img_part_list", differencePartCodeImgList);
        img_discrepancy.put("excess_img_list", excess_img_list);
        resultMap.put("img_file_list", img_discrepancy);

        return new ResponseEntity<>(resultMap, HttpStatus.OK);
    }

    //    @DS("erp")
    @Override
    public ResponseEntity<Object> getErpParts(Map<String, Object> paramMap) {

        return new ResponseEntity<>(erpProviderClient.getErpParts(paramMap), HttpStatus.OK);
    }

    @Override
    public ResponseEntity<Object> getErpInventory(Map<String, Object> paramMap) {
        return new ResponseEntity<>(erpProviderClient.getErpInventory(paramMap), HttpStatus.OK);
    }


}

